package cn.com.homeyoda.aimate.aihealth.ui.my.family.info;

import static android.view.View.GONE;
import static android.view.View.INVISIBLE;
import static android.view.View.VISIBLE;
import static cn.com.homeyoda.aimate.aihealth.utils.AppConstants.DELETE_FAMILY_MEMBER;
import static cn.com.homeyoda.aimate.aihealth.utils.AppConstants.DELETE_VIDEO_SHARE;
import static cn.com.homeyoda.aimate.aihealth.utils.AppConstants.MEMBER;
import static cn.com.homeyoda.aimate.aihealth.utils.AppConstants.UPDATE_MEMBER;
import static cn.com.homeyoda.aimate.aihealth.utils.AppConstants.UPLOAD_VIDEO_SHARE;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.Switch;
import android.widget.TextView;

import androidx.cardview.widget.CardView;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.afollestad.materialdialogs.MaterialDialog;
import com.google.android.material.button.MaterialButton;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.wzq.mvvmsmart.utils.GlideLoadUtils;
import com.wzq.mvvmsmart.utils.ToastUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import cn.com.homeyoda.aimate.aihealth.BR;
import cn.com.homeyoda.aimate.aihealth.R;
import cn.com.homeyoda.aimate.aihealth.app.AppViewModelFactory;
import cn.com.homeyoda.aimate.aihealth.base.BaseActivity;
import cn.com.homeyoda.aimate.aihealth.bean.FamilyMembersBean;
import cn.com.homeyoda.aimate.aihealth.bean.UploadVideoShareBean;
import cn.com.homeyoda.aimate.aihealth.bean.VideoShareBean;
import cn.com.homeyoda.aimate.aihealth.databinding.ActivityMemberInfoBinding;
import cn.com.homeyoda.aimate.aihealth.ui.videoinspect.ImproveInfoActivity;
import cn.com.homeyoda.aimate.aihealth.views.CenterDialog;

public class MemberInfoActivity extends BaseActivity<ActivityMemberInfoBinding, MemberInfoViewModel> implements View.OnClickListener {

    private MemberInfoAdapter memberInfoAdapter;

    private final String[] shareTimes = {"长期", "7天", "30天"};
    private final String[] shareRecordTimes = {"所有记录", "前7天记录", "前30天记录"};

    private FamilyMembersBean.DataBean.FamilyMembers member;

    private boolean isFileSharingObserve;
    private MaterialDialog permissionDialog;
    private MaterialDialog fileSharingDialog;
    private VideoShareBean.DataBean videoShareDetail;

    public static void start(Context context, FamilyMembersBean.DataBean.FamilyMembers member) {
        Intent starter = new Intent(context, MemberInfoActivity.class);
        starter.putExtra(MEMBER, member);
        context.startActivity(starter);
    }

    @Override
    public MemberInfoViewModel initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(MemberInfoViewModel.class);
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_member_info;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public void initData() {
        super.initData();
        member = getIntent().getParcelableExtra(MEMBER);
        if (member == null) {
            finish();
            return;
        }
        viewModel.isUpdateMember(member.getId(), member.getFaceId(), member.getUserId());

        initView();
    }

    private void initView() {
        binding.titleBar.ivBack.setOnClickListener(this);
        binding.titleBar.tvTitle.setText(getString(R.string.member_info));
        binding.tvDeleteMember.setOnClickListener(this);
        binding.tvEditInfo.setOnClickListener(this);
        binding.btnInviteFriends.setOnClickListener(this);

        setMemberInfo();

    }

    private void setMemberInfo() {
        GlideLoadUtils.loadImg(binding.ivMemberAvatar, member.getAvatar(), R.mipmap.ic_member1);
        binding.tvMemberName.setText(member.getName());
        binding.tvMemberGender.setText(member.getStringSex());
        binding.tvMemberAge.setText(member.getAge());

        binding.tvMemberWeightValue.setText(member.getStringWeight());
        binding.tvMemberHeightValue.setText(member.getStringHeight());
        binding.tvMemberHistoryValue.setText(member.getChronics());
    }

    private void initRecyclerView() {

        memberInfoAdapter = new MemberInfoAdapter(R.layout.health_record_item);
        binding.setLayoutManager(new LinearLayoutManager(this));
        DividerItemDecoration divider = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(this, R.drawable.divider_transparent_20));
        binding.rvHealthRecord.addItemDecoration(divider);
        binding.setAdapter(memberInfoAdapter);
        memberInfoAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            viewModel.getVideoShare(member.getId(), true);
            showPermissionDialog();
        });

    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();

        viewModel.isUpdateBean.observe(this, isUpdateBean -> {
            if (isUpdateBean.isUpdate()) {
                viewModel.getVideoShareList(member.getId());
                initRecyclerView();
                viewModel.videoShareList.observe(this, shareList -> {
                    if (memberInfoAdapter == null) return;
                    memberInfoAdapter.setNewData(shareList);
                });
            } else {
                binding.tvEditInfo.setVisibility(INVISIBLE);
                binding.ivEditInfo.setVisibility(GONE);
                binding.llHealthRecordSharing.setVisibility(GONE);
                binding.btnInviteFriends.setVisibility(GONE);
                binding.llBoundedAccount.setVisibility(VISIBLE);
                GlideLoadUtils.loadImg(binding.ivOtherMemberAvatar, isUpdateBean.getAvatar(), R.mipmap.ic_member1);
                binding.tvOtherMemberPhoneNumber.setText(isUpdateBean.getPhone());
            }
        });

        LiveEventBus.get(DELETE_FAMILY_MEMBER, Boolean.class).observe(this, aBoolean -> {
            if (aBoolean) {
                finish();
            }
        });

        LiveEventBus.get(UPDATE_MEMBER, FamilyMembersBean.DataBean.FamilyMembers.class).observe(this, member -> {
            this.member = member;
            setMemberInfo();
        });

        LiveEventBus.get(UPLOAD_VIDEO_SHARE, Boolean.class).observe(this, aBoolean -> {
            if (fileSharingDialog != null) {
                fileSharingDialog.dismiss();
                MaterialButton btnNextStep = fileSharingDialog.getView().findViewById(R.id.btn_next_step);
                ConstraintLayout clStepOne = fileSharingDialog.getView().findViewById(R.id.cl_step_one);
                ConstraintLayout clStepTwo = fileSharingDialog.getView().findViewById(R.id.cl_step_two);
                btnNextStep.setVisibility(VISIBLE);
                clStepOne.setVisibility(VISIBLE);
                clStepTwo.setVisibility(GONE);
                viewModel.getVideoShareList(member.getId());
            }
            if (permissionDialog != null) {
                permissionDialog.dismiss();
            }
        });

        LiveEventBus.get(DELETE_VIDEO_SHARE, Boolean.class).observe(this, aBoolean -> {
            if (permissionDialog != null) {
                ToastUtils.showLong("共享档案权限已撤销");
                permissionDialog.dismiss();
            }
        });

    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_back) {
            finish();
        } else if (id == R.id.tv_delete_member) {
            new CenterDialog(this, getString(R.string.delete_member_hint), () ->
                    viewModel.deleteFamilyMember(member.getFaceId())).show();
        } else if (id == R.id.tv_edit_info) {
            ImproveInfoActivity.start(this, member);
        } else if (id == R.id.btn_invite_friends) {
            showFileSharingDialog(member.getFaceId());
        }
    }

    /**
     * 编辑权限
     */
    private void showPermissionDialog() {
        if (permissionDialog != null) {
            permissionDialog.show();
            return;
        }
        permissionDialog = new MaterialDialog.Builder(this)
                .customView(R.layout.dialog_modify_permission, false)
                .show();
        ImageView ivAvatar = permissionDialog.getView().findViewById(R.id.iv_member_avatar);
        TextView tvPhoneNumber = permissionDialog.getView().findViewById(R.id.tv_phone_number);
        TextView tvExpiredTime = permissionDialog.getView().findViewById(R.id.tv_expired_time);

        Switch sAllHealthIndex = permissionDialog.getView().findViewById(R.id.switch_all_health_index);
        Switch sHeartRate = permissionDialog.getView().findViewById(R.id.switch_heart_rate);
        Switch sBloodOxygen = permissionDialog.getView().findViewById(R.id.switch_blood_oxygen);
        Switch sRespiratoryRate = permissionDialog.getView().findViewById(R.id.switch_respiratory_rate);

        CardView cvViewRecordTime = permissionDialog.getView().findViewById(R.id.cv_view_record_time);
        TextView tvRecordTime = permissionDialog.getView().findViewById(R.id.tv_record_time);

        CardView cvViewShareTime = permissionDialog.getView().findViewById(R.id.cv_view_share_time);
        TextView tvShareTime = permissionDialog.getView().findViewById(R.id.tv_share_time);

        viewModel.videoSharePermission.observe(this, videoShareDetailBean -> {
            videoShareDetail = videoShareDetailBean;
            // TODO: 2025/4/20 缺少手机号和头像
            ivAvatar.setImageResource(R.mipmap.ic_member2);
            tvPhoneNumber.setText("15866668888");
            tvExpiredTime.setText("共享健康档案权限\n" + videoShareDetail.getExamineDays() + "天后过期");

            List<String> configs = videoShareDetail.getConfigs();
            sAllHealthIndex.setChecked(configs.size() >= 3);
            sHeartRate.setChecked(configs.contains("1"));
            sBloodOxygen.setChecked(configs.contains("2"));
            sRespiratoryRate.setChecked(configs.contains("3"));

            int recordIndex = videoShareDetail.getRemainDays() >= shareRecordTimes.length ? 1 : videoShareDetail.getRemainDays();
            tvRecordTime.setText(shareRecordTimes[recordIndex]);
            int shareIndex = videoShareDetail.getShareDays() >= shareRecordTimes.length ? 1 : videoShareDetail.getShareDays();
            tvShareTime.setText(shareTimes[shareIndex]);

        });

        sAllHealthIndex.setOnClickListener(v -> {
            boolean isChecked = sAllHealthIndex.isChecked();
            sHeartRate.setChecked(isChecked);
            sBloodOxygen.setChecked(isChecked);
            sRespiratoryRate.setChecked(isChecked);
            List<String> configs = videoShareDetail.getConfigs();
            configs.clear();
            if (isChecked) {
                configs.add("1");
                configs.add("2");
                configs.add("3");
            }
        });
        sHeartRate.setOnCheckedChangeListener((buttonView, isChecked) -> setConfigs(isChecked, "1", sAllHealthIndex));
        sBloodOxygen.setOnCheckedChangeListener((buttonView, isChecked) -> setConfigs(isChecked, "2", sAllHealthIndex));
        sRespiratoryRate.setOnCheckedChangeListener((buttonView, isChecked) -> setConfigs(isChecked, "3", sAllHealthIndex));

        cvViewRecordTime.setOnClickListener(v -> showShareRecordDialog(tvRecordTime));
        cvViewShareTime.setOnClickListener(v -> showShareTimeDialog(tvShareTime));

        permissionDialog.getView().findViewById(R.id.btn_undo).setOnClickListener(v -> {
            if (videoShareDetail != null) {
                viewModel.deleteVideoShare(videoShareDetail.getId());
            }
        });

        permissionDialog.getView().findViewById(R.id.btn_save).setOnClickListener(v ->
                updateVideoShare(tvPhoneNumber.getText().toString(), true));

        if (permissionDialog.getWindow() != null) {
            permissionDialog.getWindow().setLayout(964, 669);
            permissionDialog.getWindow().setBackgroundDrawable(new android.graphics.drawable.ColorDrawable(0));
        }
    }

    /**
     * 档案共享
     */
    private void showFileSharingDialog(String faceId) {
        viewModel.faceInfo(faceId);
        if (fileSharingDialog != null) {
            fileSharingDialog.show();
            return;
        }

        fileSharingDialog = new MaterialDialog.Builder(this)
                .customView(R.layout.dialog_file_sharing, false)
                .show();
        ImageView ivAvatar = fileSharingDialog.getView().findViewById(R.id.iv_member_avatar);
        TextView tvMemberName = fileSharingDialog.getView().findViewById(R.id.tv_member_name);
        TextView tvMemberGender = fileSharingDialog.getView().findViewById(R.id.tv_member_gender);
        TextView tvMemberAge = fileSharingDialog.getView().findViewById(R.id.tv_member_age);

        Switch sAllHealthIndex = fileSharingDialog.getView().findViewById(R.id.switch_all_health_index);
        Switch sHeartRate = fileSharingDialog.getView().findViewById(R.id.switch_heart_rate);
        Switch sBloodOxygen = fileSharingDialog.getView().findViewById(R.id.switch_blood_oxygen);
        Switch sRespiratoryRate = fileSharingDialog.getView().findViewById(R.id.switch_respiratory_rate);

        CardView cvViewRecordTime = fileSharingDialog.getView().findViewById(R.id.cv_view_record_time);
        TextView tvRecordTime = fileSharingDialog.getView().findViewById(R.id.tv_record_time);

        CardView cvViewShareTime = fileSharingDialog.getView().findViewById(R.id.cv_view_share_time);
        TextView tvShareTime = fileSharingDialog.getView().findViewById(R.id.tv_share_time);

        sAllHealthIndex.setOnClickListener(v -> {
            boolean isChecked = sAllHealthIndex.isChecked();
            sHeartRate.setChecked(isChecked);
            sBloodOxygen.setChecked(isChecked);
            sRespiratoryRate.setChecked(isChecked);
            List<String> configs = videoShareDetail.getConfigs();
            configs.clear();
            if (isChecked) {
                configs.add("1");
                configs.add("2");
                configs.add("3");
            }
        });
        sHeartRate.setOnCheckedChangeListener((buttonView, isChecked) -> setConfigs(isChecked, "1", sAllHealthIndex));
        sBloodOxygen.setOnCheckedChangeListener((buttonView, isChecked) -> setConfigs(isChecked, "2", sAllHealthIndex));
        sRespiratoryRate.setOnCheckedChangeListener((buttonView, isChecked) -> setConfigs(isChecked, "3", sAllHealthIndex));

        cvViewRecordTime.setOnClickListener(v -> showShareRecordDialog(tvRecordTime));
        cvViewShareTime.setOnClickListener(v -> showShareTimeDialog(tvShareTime));

        sAllHealthIndex.setChecked(true);
        sHeartRate.setChecked(true);
        sBloodOxygen.setChecked(true);
        sRespiratoryRate.setChecked(true);
        tvRecordTime.setText(shareRecordTimes[1]);
        tvShareTime.setText(shareTimes[1]);

        MaterialButton btnNextStep = fileSharingDialog.getView().findViewById(R.id.btn_next_step);
        ConstraintLayout clSearchResult = fileSharingDialog.getView().findViewById(R.id.cl_search_result);
        ImageView icShareMemberAvatar = fileSharingDialog.getView().findViewById(R.id.iv_share_member_avatar);
        TextView tvPhoneNumber = fileSharingDialog.getView().findViewById(R.id.tv_phone_number);
        btnNextStep.setOnClickListener(v -> {
            btnNextStep.setVisibility(GONE);
            ConstraintLayout clStepOne = fileSharingDialog.getView().findViewById(R.id.cl_step_one);
            ConstraintLayout clStepTwo = fileSharingDialog.getView().findViewById(R.id.cl_step_two);
            clStepOne.setVisibility(GONE);
            clStepTwo.setVisibility(VISIBLE);

            RadioGroup rgShareType = fileSharingDialog.getView().findViewById(R.id.rg_share_type);
            LinearLayout llWechatShare = fileSharingDialog.getView().findViewById(R.id.ll_wechat_share);
            ConstraintLayout clPhoneNumberShare = fileSharingDialog.getView().findViewById(R.id.cl_phone_number_share);

            EditText etSearch = fileSharingDialog.getView().findViewById(R.id.et_search);
            MaterialButton btnSearch = fileSharingDialog.getView().findViewById(R.id.btn_search);
            btnSearch.setOnClickListener(v1 -> viewModel.queryLink(etSearch.getText().toString()));

            MaterialButton btnInvite = fileSharingDialog.getView().findViewById(R.id.btn_invite);
            btnInvite.setOnClickListener(v1 -> updateVideoShare(tvPhoneNumber.getText().toString(), false));

            rgShareType.setOnCheckedChangeListener((group, checkedId) -> {
                if (checkedId == R.id.rb_qr_code_share) {
                    llWechatShare.setVisibility(VISIBLE);
                    clPhoneNumberShare.setVisibility(GONE);
                } else {
                    llWechatShare.setVisibility(GONE);
                    clPhoneNumberShare.setVisibility(VISIBLE);
                }
            });
        });

        if (fileSharingDialog.getWindow() != null) {
            fileSharingDialog.getWindow().setLayout(964, 669);
            fileSharingDialog.getWindow().setBackgroundDrawable(new android.graphics.drawable.ColorDrawable(0));
        }

        if (isFileSharingObserve) return;
        viewModel.faceInfoData.observe(this, faceInfoBean -> {
            videoShareDetail = new VideoShareBean.DataBean();
            videoShareDetail.setFaceInfoId(faceInfoBean.getFaceId());
            videoShareDetail.setName(faceInfoBean.getName());
            videoShareDetail.setSex(Integer.parseInt(faceInfoBean.getSex()));
            videoShareDetail.setAge(Integer.parseInt(faceInfoBean.getAge()));
            videoShareDetail.setShareDays(7);
            videoShareDetail.setExamineDays(7);
            videoShareDetail.setRemainDays(7);
            videoShareDetail.setConfigs(new ArrayList<>(Arrays.asList("1", "2", "3")));

            GlideLoadUtils.loadImg(ivAvatar, faceInfoBean.getAvatar(), R.mipmap.ic_member1);
            tvMemberName.setText(faceInfoBean.getName());
            tvMemberGender.setText(TextUtils.equals(faceInfoBean.getSex(), "1") ? "男" : "女");
            tvMemberAge.setText(faceInfoBean.getAge() + "岁");
        });

        viewModel.queryLinkData.observe(this, linkData -> {
            if (linkData == null || TextUtils.isEmpty(linkData.getPhone())) {
                ToastUtils.showShort("未搜到用户信息");
                return;
            }
            clSearchResult.setVisibility(VISIBLE);
            GlideLoadUtils.loadImg(icShareMemberAvatar, linkData.getAvatar(), R.mipmap.ic_member1);
            tvPhoneNumber.setText(linkData.getPhone());
        });
        isFileSharingObserve = true;
    }

    private void updateVideoShare(String phoneNumber, boolean isUpdate) {
        if (videoShareDetail != null) {
            UploadVideoShareBean bean = new UploadVideoShareBean();
            bean.setFaceInfoId(videoShareDetail.getFaceInfoId());
            bean.setLink(phoneNumber);
            bean.setExamineDays(videoShareDetail.getExamineDays());
            bean.setShareDays(videoShareDetail.getShareDays());
            long currentTime = System.currentTimeMillis();
            bean.setStartTime(currentTime);
            bean.setEndTime(currentTime + 1000L * 60 * 60 * 24 * videoShareDetail.getShareDays());
            bean.setConfigIds(videoShareDetail.getConfigs());
            if (isUpdate) {
                viewModel.updateVideoShare(bean);
            } else {
                viewModel.addVideoShare(bean);
            }
        }
    }

    private void setConfigs(boolean isChecked, String number, Switch sAllHealthIndex) {
        List<String> configs = videoShareDetail.getConfigs();
        if (isChecked) {
            configs.add(number);
            if (configs.size() >= 3) {
                sAllHealthIndex.setChecked(true);
            }
        } else {
            configs.remove(number);
            sAllHealthIndex.setChecked(false);
        }
    }

    /**
     * 选择记录时长
     */
    private void showShareRecordDialog(TextView tvRecordTime) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("选择记录时长");
        builder.setItems(shareRecordTimes, (dialog, index) -> {
            if (videoShareDetail != null) {
                videoShareDetail.setExamineDays(getDays(index));
            }
            tvRecordTime.setText(shareRecordTimes[index]);
        });
        builder.show();
    }

    private static int getDays(int index) {
        int days = 0;
        if (index == 1) {
            days = 7;
        } else if (index == 2) {
            days = 30;
        }
        return days;
    }

    /**
     * 选择分享时长
     */
    private void showShareTimeDialog(TextView tvShareTime) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("选择分享时长");
        builder.setItems(shareTimes, (dialog, index) -> {
            if (videoShareDetail != null) {
                videoShareDetail.setShareDays(getDays(index));
            }
            tvShareTime.setText(shareTimes[index]);
        });
        builder.show();
    }

}